from django.shortcuts import render, redirect, reverse
from web import models
from utils import cos
from web.forms.account import SetPwdForm

def setting(request, project_id):
    return render(request, 'setting/setting.html')


# 删除项目
def setting_delete(request, project_id):
    if request.method == 'POST':
        # 1 数据库删除项目
        # 获取要删除的项目名称
        project_name = request.POST.get('project_name', '')
        project_obj = models.Project.objects.filter(id=project_id, name=project_name).first()
        if not project_obj:
            return render(request, 'setting/setting_delete.html', {'error': '项目不存在'})

        # 保证当前用户和项目创建者一致
        if request.tracer.user.username != project_obj.creator.username:
            return render(request, 'setting/setting_delete.html', {'error': '无权删除此项目'})

        # 2 cos对象存储删除项目对应的桶 和 文件 、碎片
        cos.delete_bucket(request.tracer.project.bucket, request.tracer.project.region)

        # 删除数据库
        project_obj.delete()
        url = reverse('project_list')
        return redirect(url)
    return render(request, 'setting/setting_delete.html')


def set_password(request,project_id):
    form =SetPwdForm(request,)
    if request.method == 'POST':
        form = SetPwdForm(request,data=request.POST)
        if form.is_valid():
            password = form.cleaned_data.get('password')
            models.UserInfo.objects.filter(id=request.tracer.user.id).update(password=password)
            return redirect('login')
        else:
            return render(request, 'setting/set_password.html',{'form':form})
    return render(request, 'setting/set_password.html',{'form':form})
